<script>
import {BASE_CONFIG} from './config/app';
import Wechat from './libs/wechat.js';
import * as LoginApi from '@/api/login.js';
import * as UserApi from '@/api/member/user.js';
import * as CenterConfigApi from '@/api/system/centerConfig.js';
import Routine from './libs/routine.js';
import themConfig from '@/utils/them/theam.js';
import {mapGetters} from "vuex";
import {getDicts} from "@/api/system/dict";
import {CENTER_CONFIG_KEY, DIC_TYPE_LIST} from "@/utils/dict.js";

export default {
  computed: mapGetters(['tabBarIndex', 'memberPermissions', 'isLogin', 'userInfo', 'schoolId', 'shareInfo']),
  globalData: {
    themConfig: themConfig,
    spid: 0,
    code: 0,
    MyMenus: [],
    windowHeight: '1000rpx',
    tabBarPages: [],
    id: 0,
    tabBarIndex: 0, // tabbar全局索引
    windows: {
      titleBarHeight: 0, //导航栏（胶囊）高度
      statusBarHeight: 0, // 状态栏高度（信号栏）
      navHeight: 0,      // 导航栏高度=菜单按钮高度+（菜单按钮与顶部距离-状态栏高度）*2
      pageBody: 0,      // 整个窗口高度-整个导航高度
      pageBodySubNav: 0,      // 整个窗口高度-整个导航高度
      tabbarH: 55,      // 底部导航栏高度
      pageWidth: 0,
    },
    applicationConfig: {}
  },
  watch: {
    // tabBarIndex:{
    //   handler(o,n){
    //     console.log("tabBarIndexChange",n);
    //     uni.$emit("tabBarIndexChange",n);
    //   },
    //   deep:true
    // }
  },

  onLaunch: function (option) {

    uni.hideTabBar();
    // 分销
    this.initDis(this, option);

    // 注册路由拦截器
    this.registerInterceptor('navigateTo');

    this.mpLogin(this, option);

    this.maLogin(this)

    this.initNavAndPageHeight(this);

    // 获取配置
    this.getContentConfig();

    // tabbar 复位
    this.tabIndexRecover();

    DIC_TYPE_LIST.forEach(item => {
      this.initDicData(item.value)
    })

    this.checkUpdate();
  },

  onShow: function () {
    this.tabIndexRecover();
  },

  methods: {

    checkUpdate() {
      // #ifdef MP
      const updateManager = wx.getUpdateManager();

      updateManager.onCheckForUpdate((res) => {
        console.log('是否有新版本：', res.hasUpdate);
      });

      updateManager.onUpdateReady(() => {
        uni.showModal({
          title: '更新提示',
          content: '新版本已经准备好，是否重启应用？',
          success(res) {
            if (res.confirm) {
              updateManager.applyUpdate();
            }
          }
        });
      });

      updateManager.onUpdateFailed(() => {
        uni.showModal({
          title: '更新失败',
          content: '新版本下载失败，请删除当前小程序后重新搜索打开',
          showCancel: false
        });
      });
      // #endif
    },

    /**
     * 获取网站配置
     */
    getContentConfig() {
      let that = this;
      CenterConfigApi.getCenterConfig(CENTER_CONFIG_KEY.APPLICATION_CONFIG.value).then(res => {
        let data = res.data;
        that.globalData.applicationConfig = data;
      }).catch(e => {
        that.globalData.applicationConfig = CENTER_CONFIG_KEY.APPLICATION_CONFIG.demoData;
      })
    },

    /**
     * 初始化字典
     */
    async initDicData(dictType) {
      let data = this.$store.state.app.dicData;
      if (data === undefined || data === null) {
        let map = new Map();
        await getDicts(dictType).then(res => {
          let datas = res.data;
          let mapV = {};
          for (const resKey in datas) {
            let item = datas[resKey];
            mapV[item.dictValue] = {
              value: item.dictValue,
              text: item.dictLabel,
              class: item.listClass
            }
          }
          map.set(dictType, mapV);
          console.log('mapV', map)
          this.$store.commit('DICT_DATA', map);
        })
      }
    },

    /**
     * 路由拦截 鉴权等其他
     * @param api 拦截API
     */
    registerInterceptor(api) {

      let that = this;

      uni.addInterceptor(api, {
        invoke(args) {
          // request 触发前拼接 url

          console.log("拦截前触发", args);

          console.log("this.isLogin",that.isLogin)

          // #ifdef H5
          console.log("Wechat.isWeixin()",Wechat.isWeixin())
          // #endif

          // 排除掉协议页面
          if (args.url.indexOf("/pages/users/privacy/index") >= 0 || args.url.indexOf("/pages/users/wechat_login/index")
              >= 0 || args.url.indexOf("/pages/users/login/index") >= 0) {
            return true;
          }


          // 登陆拦截
          if (!that.isLogin) {
            // #ifdef H5
            if (Wechat.isWeixin()) {
              that.mpAuth(that, null, 'snsapi_userinfo');
              return false;
            }
            // #endif

            // #ifdef MP
            that.maLogin(that)
            return false;
            // #endif

            uni.navigateTo({ url: '/pages/users/login/index' });

            return false;
          }else {
            // #ifdef H5

            if (Wechat.isWeixin() && !that.userInfo.unionId) {
              that.mpAuth(that, null, 'snsapi_userinfo');
              return false;
            }
            // #endif
          }


          // 信息是否注册拦截
          if (args.url.indexOf("/pages/school/add-order/index") >= 0) {

            // 是否认证注册信息
            if (that.userInfo.phone === undefined || that.userInfo.phone === null || that.userInfo.phone === '') {
              uni.showToast({
                title: '需要先注册信息......',
                duration: 2000,
                icon: 'none'
              });

              setTimeout(() => {
                uni.navigateTo({
                  url: '/pages/users/user_info/index',
                })
              }, 500)

              return false;
            }

            // 是否选择学校
            if (that.schoolId === undefined || that.schoolId === null || that.schoolId === '') {

              uni.showToast({
                title: '需要先选择学校.....',
                duration: 2000,
                icon: 'none'
              });

              setTimeout(() => {
                uni.$emit("tabBarIndexChange", 3);
                that.$store.commit('SET_TAB_BAR_IDX', 3);
                uni.switchTab({
                  "url": '/pages/user/index'
                })
              }, 500)
              return false;
            }

            // 发布模式还是购买模式

            if (that.globalData.applicationConfig.createOrderModel.createOrderModel === 'BUY') {
              let queryString = args.url.split('?')[1]; // 取出 ? 之后的部分
              // console.log("queryString", queryString)

              if (queryString) {
                let keyValue = queryString.split("=");
                if (keyValue.length > 1) {
                  queryString = keyValue[1];
                }
              }

              let paramsValue = JSON.parse(decodeURIComponent(queryString))
              // console.log("paramsValue", paramsValue)
              if (paramsValue.taskCode !== 'TASK03') {
                let redirectUrl = "/pages/school/buy-model/index"
                let url = args.url.replaceAll("/pages/school/add-order/index", redirectUrl);
                args.url = url;
                console.log("url", url)
              }
            }
          }
          return true;
        },
        success(args) {
          // 请求成功后，修改code值为1
          console.log("成功回调拦截", args)
        },
        fail(err) {
          console.log("失败回调拦截", err)
        },
        complete(res) {
          // console.log('完成回调拦截', res)
        }
      });
    },

    initNavAndPageHeight(that) {

      let menuButtonObject = {
        height: 0,
        top: 0,
      }

      // #ifndef H5 || APP-PLUS || MP-ALIPAY || MP
      menuButtonObject = uni.getMenuButtonBoundingClientRect(); //获取菜单按钮（右上角胶囊按钮）的布局位置信息。坐标信息以屏幕左上角为原点。
      // #endif

      uni.getSystemInfo({ //获取系统信息
        success: res => {
          //导航栏高度=菜单按钮高度+（菜单按钮与顶部距离-状态栏高度）*2
          let navHeight = menuButtonObject.height + (menuButtonObject.top - res.statusBarHeight) * 2;
          // 导航栏（胶囊）高度
          that.globalData.windows.titleBarHeight = navHeight;
          //  状态栏（顶部）高度
          that.globalData.windows.statusBarHeight = res.statusBarHeight

          let windowHeight = res.windowHeight;
          if (this.$util.isOs()) {
            windowHeight = (window.innerHeight || document.documentElement.clientHeight)
          }
          that.globalData.windows.pageBody = windowHeight - navHeight
          that.globalData.windows.pageBodySubNav = res.windowHeight - navHeight - 44
          that.globalData.windows.pageWidth = res.windowWidth

          console.log("windows", res)
        },
        fail(err) {
          console.log(err);
        }
      })
    },

    /**
     * 小程序静默登录
     * @param that
     * @param option
     */
    maLogin(that) {
      // #ifdef MP
      if (!that.$store.getters.isLogin) {

        uni.showLoading({
          title: '登陆中...',
          mask: true
        });

        // 解析 shareInfo，避免解析错误
        let userCode = "";
        // 解析 shareInfo，避免解析错误
        if (that.shareInfo) {
          try {
            userCode = JSON.parse(this.shareInfo).code;
          } catch (e) {
            console.error("解析 shareInfo 失败", e);
          }
        }

        Routine.getCode().then(code => {

          // 调用微信 H5 登录接口
          LoginApi.loginWxMa({
            "appId": BASE_CONFIG.appId,
            "wxCode": code,
            "loginType": BASE_CONFIG.LoginType.MaAuth,
            "userCode": userCode
          }).then(res => {
            console.log("登录结果", res);
            uni.hideLoading();

            // 存储 token
            that.$store.commit("LOGIN", {
              'token': res.data.accessToken
            });

            // 获取用户信息
            that.getUserInfo(res.data,res=>{
              uni.reLaunch({
                url: '/pages/index/index'
              });
            });

          }).catch(err => {
            uni.hideLoading();
            console.error("微信登录失败", err);
          });

        }).catch(res => {
          uni.hideLoading();
        });
      }
      // #endif
    },

    // 静默授权登陆
    mpLogin(that, option) {
      // #ifdef H5
      // 静默登录的情况一：微信公众号
      if (!that.$store.getters.isLogin && Wechat.isWeixin()) {
        let userCode = '';
        if (option && option.query && option.query.hasOwnProperty('code')) {
          // 解析 shareInfo，避免解析错误
          if (this.shareInfo) {
            try {
              userCode = JSON.parse(this.shareInfo).code;
            } catch (e) {
              console.error("解析 shareInfo 失败", e);
            }
          }

          // 调用微信 H5 登录接口
          LoginApi.loginWxH5({
            "appId": BASE_CONFIG.appId,
            "wxCode": option.query.code,
            "loginType": BASE_CONFIG.LoginType.MpAuth,
            "userCode": userCode
          }).then(res => {
            console.log("登录结果", res);

            // 存储 token
            that.$store.commit("LOGIN", {
              'token': res.data.accessToken
            });

            // 获取用户信息
            that.getUserInfo(res.data, res => {
              // 刷新页面
              uni.hideLoading();
              window.location.replace(BASE_CONFIG.H5WebHost);
            });

          }).catch(err => {
            uni.hideLoading();
            console.error("微信登录失败", err);
          });
        } else {
          this.mpAuth(that, option, 'snsapi_base')
        }
      } else {
        if (option && option.query && option.query.hasOwnProperty('code')) {

          // 调用微信 H5 登录接口
          LoginApi.loginWxH5({
            "appId": BASE_CONFIG.appId,
            "wxCode": option.query.code,
            "loginType": BASE_CONFIG.LoginType.MpAuth,
          }).then(res => {
            console.log("登录结果", res);

            // 存储 token
            that.$store.commit("LOGIN", {
              'token': res.data.accessToken
            });

            // 获取用户信息
            that.getUserInfo(res.data, res => {
              // 刷新页面
              uni.hideLoading();
              window.location.replace(BASE_CONFIG.H5WebHost);
            });

          }).catch(err => {
            uni.hideLoading();
            console.error("微信登录失败", err);
          });
        }
      }
      // #endif
    },

    // 公众号去授权获取回调code
    mpAuth(that, option, scope) {
      uni.showLoading({
        title: '登陆中...',
        mask: true
      });

      /**
       * 应用授权作用域，snsapi_base （不弹出授权页面，直接跳转，只能获取用户openid）
       * snsapi_userinfo （弹出授权页面，可通过openid拿到昵称、性别、所在地。并且， 即使在未关注的情况下，只要用户授权，也能获取其信息 ）
       */
      let scopeV = scope || 'snsapi_userinfo';
      LoginApi.getMpWebAuthUrl({
        "appId": BASE_CONFIG.appId,
        "scope": scopeV,
        "redirectUri": BASE_CONFIG.H5WebHost
      }).then(res => {
        window.location.replace(res.data.authUrl);
      }).catch(err => {
        console.error("获取微信授权 URL 失败", err);
      });
    },

    getUserInfo(data, callback) {
      this.$store.commit("SETUID", data.userId);
      this.$store.commit("OPENID", data.openId);
      UserApi.getUserInfo().then(res => {
        this.$store.commit("UPDATE_USERINFO", res.data);
        if (callback) {
          callback(res.data)
        }
      })
    },

    // 分销
    initDis(that, option) {
      let _this = this;

      // #ifndef MP
      if (option.query.hasOwnProperty('shareCode')) {
        let data = decodeURIComponent(option.query.shareCode);
        console.log("邀请码", data)
        _this.$store.commit('SET_SHARE_CODE', JSON.stringify({"code": data, 'userName': data, 'expireTime': null}));
      }
      // #endif

      // #ifdef MP
      console.log("option.scene", option.scene)
      if (option.scene) {
        try {
          let scene = decodeURIComponent(option.scene);
          let uCode = scene.split("=")[0];
          _this.$store.commit('SET_SHARE_CODE', JSON.stringify({"code": uCode, 'userName': '', 'expireTime': null}));
        } catch (e) {
          console.error("解析 userCode 失败", e);
        }
      }
      // #endif

    },

    // tab复位还原
    tabIndexRecover() {
      // #ifdef H5
      let idnex = 0;
      if (location.href.indexOf("/pages") < 0) {
        idnex = 0;
      } else if (location.href.indexOf("/pages/school/order/index") >= 0) {
        idnex = 1;
      } else if (location.href.indexOf("/pages/school/deliveryOrder/index") >= 0) {
        idnex = 2;
      } else if (location.href.indexOf("/pages/user/index") >= 0) {
        idnex = 3;
      } else {
        idnex = this.tabBarIndex || 0
      }
      this.globalData.tabBarIndex = idnex;
      console.log("tabBarIndex", idnex);
      // #endif
    }
  },

  async mounted() {
    // 读取用户的基本信息
    if (this.$store.getters.isLogin && !this.$Cache.get('USER_INFO')) {
      await this.$store.dispatch('USERINFO');
    }
  },

  navigateTo: function (params, url) {
    this.$store.commit('SET_URL_PARAMS', params);
    uni.navigateTo({
      url: url,
    })
  }
}
</script>
<style>
@import url("@/plugin/animate/animate.min.css");
@import 'static/css/base.css';
@import 'static/iconfont/iconfont.css';
@import 'static/css/guildford.css';
@import 'static/css/style.scss';

/* 条件编译，仅在H5平台生效 */
// #ifdef H5
body::-webkit-scrollbar,
html::-webkit-scrollbar {
  display: none;
}

// #endif
view {
  box-sizing: border-box;
}

.bg-color-red {
  background-color: #E93323 !important;
}

.syspadding {
  padding-top: var(--status-bar-height);
}

.flex {
  display: flex;
}

.uni-scroll-view::-webkit-scrollbar {
  /* 隐藏滚动条，但依旧具备可以滚动的功能 */
  display: none
}

::-webkit-scrollbar {
  width: 0;
  height: 0;
  color: transparent;
}
</style>
